package io.tim.mvc_f2.helper;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import io.tim.mvc_f2.util.ReflectionUtil;

/**
 * Bean 助手类
 *
 * @author zhangnan
 * @date 2017年3月10日
 *
 */
public final class BeanHelper {

	/**
	 * 定义 Bean 映射（用于存放 Bean 类与 Bean 实例的映射关系
	 */
	private static final Map<Class<?>, Object> BEAN_MAP = new HashMap<Class<?>, Object>();
	
	static {
		Set<Class<?>> beanClassSet = ClassHelper.getBeanClassSet();
		for (Class<?> beanClass : beanClassSet) {
			Object bean = ReflectionUtil.newInstance(beanClass);
			BEAN_MAP.put(beanClass, bean);
		}
	}
	
	/**
	 * 获取 Bean 映射
	 */
	public static Map<Class<?>, Object> getBeanMap() {
		return BEAN_MAP;
	}
	
	/**
	 * 获取某一 Class<T> 的实例
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBean(Class<T> cls) {
		if (!BEAN_MAP.containsKey(cls)) {
			throw new RuntimeException("cannot get bean by class: " + cls);
		}
		return (T) BEAN_MAP.get(cls);
	}
}
